<?php
/**
 * Created by PhpStorm.
 * User: i5_131009a
 * Date: 2015/12/23
 * Time: 15:12
 */

if(php_sapi_name() !== "cli"){
    header("Content-type:text/html;charset=utf-8");
    echo "请用cli模式运行";
    return;
}
define("DATABASE_HOST","127.0.0.1");
define("DATABASE_USERNAME","root");
define("DATABASE_PASSWD","");
define("DATABASE_BASE_NAME","test");
define("DATABASE_PORT",3306);

define("JSON_DIR","./json/");
define("LINE_EOF","\n");
define("FILE_EXT","json");
$mysql = new mysqli();
$mysql->connect(DATABASE_HOST,DATABASE_USERNAME,DATABASE_PASSWD,DATABASE_BASE_NAME,DATABASE_PORT);
$opt = getopt("d:t:e:f",["help::"]);
if(isset($opt["help"])){
    $helpStr =  "-d 设置输出目录默认当前目录".LINE_EOF;
    $helpStr .= "-t 设置指定表名默认所有表,如需导出多张表请用 , 隔开".LINE_EOF;
    $helpStr .= "-e 设置文件后缀默认json".LINE_EOF;
    $helpStr .= "-f 设置文件是否覆盖默认不覆盖".LINE_EOF;
    echo $helpStr;
    return;
}

if(isset($opt["d"])){
    $jsonDir = $opt["d"];
    if(substr($jsonDir,-1) != "/"){
        $jsonDir .= "/";
    }
}else{
    $jsonDir = "./";
}

if(isset($opt["f"])){
    $cover = false;
}else{
    $cover = true;
}

if(isset($opt["e"])){
    $jsonExt = $opt["e"];
}else{
    $jsonExt = FILE_EXT;
}

if(isset($opt["t"])){

    $tableNameArray = explode(",",$opt["t"]);
    foreach($tableNameArray as $tableName){
        $path = $jsonDir . "{$tableName}." . $jsonExt;
        echo "生成: {$path}" . LINE_EOF;
        createJsonByTableName($path,$cover,$mysql,$tableName);
    }
}else{
    createAllJson($jsonDir,$cover,$mysql,$jsonExt);
}

$mysql->close();

function createAllJson($dir,$cover,$mysql,$ext)
{
    $result = $mysql->query("show tables;");

    $data = mysqli_fetch_all($result);

    if (!file_exists($dir)) {
        echo "文件夹不存在" . LINE_EOF;
    }

    foreach ($data as $oneTable) {
        $path = $dir . "{$oneTable[0]}." . $ext;
        echo "生成: {$path}" . LINE_EOF;
        createJsonByTableName($path,$cover,$mysql,$oneTable[0]);
    }
}

function createJsonByTableName($path,$cover,$mysql,$tableName){
    if(file_exists($path) && $cover){
        echo "文件存在跳过".LINE_EOF;
        return;
    }
    $jsonData = array();

    $jsonData["tableName"] = $tableName;

    $rowSet["dataStartRow"] = 3;
    $rowSet["columnNameRow"] = 2;
    $rowSet["columnNameRow"] = 2;

    $columnName = getDatabaseTableColumn($mysql,$tableName);
    if($columnName == false){
        return;
    }
    $columnSet = array_combine($columnName,$columnName);

    $sourceDataSet["sheet"] = 0;
    $sourceDataSet["rowSet"] = $rowSet;
    $sourceDataSet["columnSet"] = $columnSet;

    $jsonData["sourceDataSet"] = $sourceDataSet;

    $jsonFile = fopen($path,"w");
    fwrite($jsonFile,formatJson(json_encode($jsonData)));
    fclose($jsonFile);
}



function getDatabaseTableColumn($mysql,$tableName){
    $result = $mysql->query("SHOW FIELDS FROM $tableName");
    if($result == false){
        echo $mysql->error.LINE_EOF;
        return false;
    }
    $result = mysqli_fetch_all($result);
    $columnList = array();
    foreach($result as $oneColumnName){
        $columnList[] = $oneColumnName[0];
    }
    return $columnList;
}


function formatJson($jsonStr){
    $strlan = strlen($jsonStr);
    $lineBreak = "\n";
    $tab = "\t";
    $formatJson = "";

    $prefix = "";
    for($i = 0; $i < $strlan; $i++){
        $char = substr($jsonStr,$i,1);

        switch ($char){
            case '{':
            case '[':
                $prefix .= $tab;
                $formatJson .= $char . $lineBreak.$prefix;
                break;
            case '}':
            case ']':
                $formatJson .= $lineBreak.$prefix . $char;
                if($prefix != $tab){
                    $prefix = substr($prefix,-count($tab));
                }else{
                    $prefix = "";
                }
                break;
            case ',':
                $formatJson .= $char.$lineBreak.$prefix;
                break;
            default:
                $formatJson .= $char;
        }

    }
    return $formatJson;
}

?>